package chapter2_9_unsafe;

import sun.misc.Unsafe;

/**
 * @author huayuhao
 * @date 2020/12/16 14:47
 */
public class TestUnsafe {

    // 获取Unsafe实例
    static final Unsafe UNSAFE = Unsafe.getUnsafe();

    // 记录变量state在类TestUnsafe中的偏移值
    static final long stateOffset;

    // state变量
    private volatile long state = 0;

    static {
        try{
            // 初始化state变量在类TestUnsafe中的偏移值
            stateOffset = UNSAFE.objectFieldOffset(TestUnsafe.class.getDeclaredField("state"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new Error(e);
        }
    }

    public static void main(String[] args) {
        TestUnsafe testUnsafe = new TestUnsafe();
        // 如果stateOffset的state变量的值为0,则更新为1
        boolean success = UNSAFE.compareAndSwapInt(testUnsafe, stateOffset, 0, 1);
        System.out.println(success);
    }

}
